package com.kuang.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.kuang.exception.ServiceException;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头Header里接收传来的参数token
        String headerToken = request.getHeader("token");
        //如果传来的token为空，则从url参数中来接收传来的token
        if(StringUtils.isBlank(headerToken)){
            headerToken = request.getParameter("token");
            //如果url里的token为空，则抛异常
        }
        if (StringUtils.isBlank(headerToken)){
            throw new ServiceException("401","请登录");
        }
        //从token中获取userId
        //JWT.decode(headerToken) 解码JTW Token
        String userId;
        try {
            userId = JWT.decode(headerToken).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new ServiceException("401","请登录");
        }
        //根据userId查询数据库
        //userId是String类型，这里要转换成int类型
        User user = userMapper.selectUserById(Integer.parseInt(userId));
        //user为空，则抛异常
        if (user == null){
            throw new ServiceException("401","请登录");
        }
        //通过用户密码加密之后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            //验证token
            jwtVerifier.verify(headerToken);
        } catch (JWTVerificationException e) {
            throw new ServiceException("401","请登录");
        }
        return true;
    }
}
